package com.ww.springboot.boot.algorithm.leetcode1;

/**
 * 描述：
 *
 * @author 🧑 ‍wanwei
 * @since 2022-08-20 16:41
 */
public class CJ排序链表 {


    public static void main(String[] args) {
        ListNode listNode = new ListNode(3, new ListNode(2));

        ListNode x = sortList(listNode);
        System.out.println(x);
    }


    /**
     * 冒泡排序 只要发现后面一个值比前面一个值小 就与其交换位置  行不通 没有前指针
     * 选择排序 在无序区每次选择一个最小值放到有序区尾部 可行 时间复杂度过高
     * 归并排序 将大任务分成小任务 再将每个小任务合并在一起
     *
     * @param head
     * @return
     */
    public static ListNode sortList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        } else if (head.next.next == null) {
            if (head.val < head.next.val) {
                return new ListNode(head.val, new ListNode(head.next.val));
            } else {
                return new ListNode(head.next.val, new ListNode(head.val));
            }
        }
        ListNode listNodeNew = null;
        while (head.next != null) {
            //1.找到最小的
            int min = findMin(head);
            //2.将找到的最小值放到新链表尾端
            if (listNodeNew == null) {
                listNodeNew = new ListNode(min);
            } else if (listNodeNew.next == null) {
                listNodeNew.next = new ListNode(min);
            } else {
                ListNode end = listNodeNew.next;
                while (end.next != null) {
                    end = end.next;
                }
                end.next = new ListNode(min);
            }
            //3.将最小值从旧队列中删除
            if (head.val == min) {
                head = head.next;
                continue;
            }
            ListNode node = head.next;
            if (node.val == min) {
                head.next = node.next;
                continue;
            }
            while (node.next.val != min) {
                node = node.next;
            }
            node.next = node.next.next;
        }

        ListNode end = listNodeNew.next;
        while (end.next != null) {
            end = end.next;
        }
        end.next = new ListNode(head.val);
        return listNodeNew;
    }

    private static int findMin(ListNode head) {
        int min = head.val;
        ListNode next = head.next;
        while (next != null) {
            if (next.val < min) {
                min = next.val;
            }
            next = next.next;
        }
        return min;
    }


    /**
     * Definition for singly-linked list.
     */
    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}
